import {messages} from "share/common";
import React from 'react'

import { Form, Upload, Icon, message, Modal, Button, Row, Col } from 'antd'
const Dragger = Upload.Dragger;
import config from 'config'
import FileViewer from 'components/file-viewer'
import 'styles/components/file-upload.scss'

import {connect} from "react-redux";
import excelImage from 'images/file-type/excel.png'
import pdfImage from 'images/file-type/pdf.png'
import pptImage from 'images/file-type/ppt.png'
import txtImage from 'images/file-type/txt.png'
import wordImage from 'images/file-type/word.png'
import unknownImage from 'images/file-type/unknown.png'
import constants from 'share/constants';

/**
 * 图片上传组件
 */
class FileUpload extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      previewVisible: false,
      previewImage: '',
      fileList: [],
      result: [],
      previewIndex: 0, //预览图片的index
      modalShow: false,
      info: null
    }
  }
  componentDidMount() {
    if (this.props.defaultFileList.splice) {
      this.showDefaultFileList(this.props.defaultFileList);
    }
  }

  componentWillReceiveProps(nextProps) {
    if(this.props.isShowDefault){
      if (nextProps.defaultFileList.splice) {
        this.showDefaultFileList(nextProps.defaultFileList);
      }
    }
  }
  //为了显示默认已经上传的图片
  showDefaultFileList=(defaultFileList)=>{
    let fileList = [];
    defaultFileList.map(attachment => {
      fileList.push({
        uid: attachment.attachmentOID,
        attachmentOID: attachment.attachmentOID,
        name: attachment.fileName,
        fileName: attachment.fileName,
        fileURL: attachment.fileURL,
        status: 'done',
        url: attachment.fileURL
      })
    });
    this.setState({ fileList, result: defaultFileList })
  };

  handleData = () => {
    let date = this.props.data ? this.props.data : {attachmentType: this.props.attachmentType};
    return date;
  };


  handleChange = (info) => {
    if (this.props.fileType) {  //控制上传图片的类型
      let isFileType = false;
      this.props.fileType.map(type => {
        info.file.type === `image/${type}` && (isFileType = true)
      });
      if (!isFileType && info.file.status !== 'removed') {
        //上传失败，图片格式错误
        // message.error(messages('components.key398'/*上传失败，图片格式错误*/));
        Modal.error({
          title: messages('components.key400'/*上传失败*/),
          content: messages('components.key398'/*上传失败，图片格式错误*/),
          okText: messages('common.ok')/*'确定'*/
        });
        return
      }
    }
    if (this.props.fileSize) {  //控制上传图片的大小
      const isLtSize = info.file.size / 1024 / 1024 <= this.props.fileSize;
      if (!isLtSize && info.file.status !== 'removed') {
        //您上传的附件已超出大小限制，请重新上传！
        // message.error(messages('components.key654',{arg1: info.file.name,arg2: this.props.fileSize}/*{arg1}大于{arg2}M*/));
        Modal.error({
          title: messages('components.key400'/*上传失败*/),
          content: messages('components.key654',{arg1: info.file.name,arg2: this.props.fileSize}/*{arg1}大于{arg2}M*/),
          okText: messages('common.ok')/*'确定'*/
        });
        return
      }
    }
    let fileList = info.fileList;
    console.log("fileList", info)
    fileList.map(file => {
      if(file.thumbUrl)
        file.url = file.thumbUrl;
    });
    this.setState({ fileList },() => {
      const status = info.file.status;
      let { result } = this.state;
      if (status === 'done') {
        message.success(`${info.file.name} ${messages('components.key399'/*上传成功*/)}`);
        this.props.setResult(result,info);
        if (!fileList.some(item => item.status !== 'done')) {
          this.setState({ result });
          this.props.onChange(result);
        }
      } else if (status === 'error') {
        // message.error(`${info.file.name} ${messages('components.key400'/*上传失败*/)}`);
        Modal.error({
          title: messages('components.key400'/*上传失败*/),
          content: `${info.file.name} ${messages('components.key400'/*上传失败*/)}`,
          okText: messages('common.ok')/*'确定'*/
        });
      }
    });
  };
  // 预览
  handlePreview = (file) => {
    let {isPreViewCallBack,handlePreViewCallBack} =this.props;
    if(isPreViewCallBack){
      handlePreViewCallBack(file);
      return;
    }
    if(this.isAllowedFile(file)){
      this.state.result.map((item, index) => {
        if (item.attachmentOID === (file.response ? file.response.attachmentOID : file.attachmentOID)) {
          this.setState({
            previewIndex: index,
            previewVisible: true
          })
        }
      });
    } else {
      window.open(file.response ? file.response.fileURL : file.fileURL, '_blank')
    }
  };

  getImage = (file) => {
    let sections = file.fileName.split('.');
    let extension = sections[sections.length - 1].toLowerCase();
    let imageExtension = ['png', 'gif', 'jpg', 'jpeg', 'bmp'];
    let wordExtension = ['doc', 'docx'];
    let pptExtension = ['ppt', 'pptx'];
    let excelExtension = ['xls', 'xlsx'];
    let txtExtension = ['txt'];
    let pdfExtension = ['pdf'];
    if(imageExtension.has(extension))
      return file.thumbnailUrl || file.fileURL;
    if(wordExtension.has(extension))
      return wordImage;
    if(pptExtension.has(extension))
      return pptImage;
    if(excelExtension.has(extension))
      return excelImage;
    if(txtExtension.has(extension))
      return txtImage;
    if(pdfExtension.has(extension))
      return pdfImage;
    return unknownImage;
  };

  isAllowedFile = (file) => {
    let sections = (file.response ? file.response.fileName : file.fileName).split('.');
    let extension = sections[sections.length - 1].toLowerCase();
    let imageExtension = ['png', 'gif', 'jpg', 'jpeg', 'bmp', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'txt', 'pdf'];
    return imageExtension.has(extension);
  };

  closeModal = () => {
    this.setState({ modalShow: false });
  };

  deleteImage = () => {
    let { result, info, fileList } = this.state;
    let required = false;
    let attachmentOid = info.response ?
      (info.response.attachmentOID || (info.response.attachmentDTO ? info.response.attachmentDTO.attachmentOID : null)) :
      info.attachmentOID;
    if(!attachmentOid)
      required = true;
    result.map((item, index) => {
      if (item.attachmentOID === attachmentOid
        || item.attachmentOID === info.uid) {
        required = this.props.handleDelete(item.id);
        required && result.splice(index, 1);
      }
    });
    if(required) {
      let currentFile = fileList.filter(item => item === info)[0];
      fileList.splice(fileList.indexOf(currentFile), 1);
    }
    this.setState({ result, info: null, modalShow: false, fileList });
    this.props.onChange(result);
  };

  remove = (info) => {
    this.setState({ modalShow:true , info:info });
    return false;
  };

  render() {
    const { previewVisible, fileList, previewIndex, result, modalShow } = this.state;
    const uploadButton = (
      <Button>
        <Icon type="upload" /> {messages('common.upload')/*上传*/}
      </Button>
    );
    const upload_headers = {
      'Authorization': 'Bearer ' + this.props.authToken.access_token
    };
    let size = this.props.fileSize ? this.props.fileSize : 10;
    return (
      <div className="file-upload">
        <div>
          <Upload
            name="file"
            multiple={this.props.multiple}
            data={this.handleData}
            action={this.props.uploadUrl}
            accept={this.props.accept}
            headers={upload_headers}
            // listType="picture-card"
            fileList={this.props.showFileName ? fileList : []}
            showUploadList={{showRemoveIcon: !this.props.disabled}}
            onPreview={this.handlePreview}
            onChange={this.handleChange}
            onRemove={this.remove}
          >
            {(fileList.length >= this.props.maxNum || this.props.disabled) ? null : uploadButton}
          </Upload>
        </div>
        {
          this.props.showMaxNum && !this.props.disabled && (
            <div>({messages('common.max.upload.attachment', {max: this.props.maxNum})/*最多上传 {max} 个附件*/})</div>
        )}
        {
          !this.props.disabled &&
            <div>
              <div>{this.props.placeHolder}</div>
            </div>
        }
        <Row type="flex" style={{ marginTop: 10 }}>
          {result.map((attachment, index) => (
            <Col className="attachment-block" key={index} onClick={() => this.handlePreview(attachment)}>
              <img src={this.getImage(attachment)}/>
            </Col>
          ))}
        </Row>
        <FileViewer
          visible={previewVisible}
          attachments={result}
          defaultIndex={previewIndex}
          onCancel={() => this.setState({previewVisible: false})}
          urlKey="fileURL"
          valueKey="attachmentOID"
        />
        <Modal
          onOk={this.deleteImage}
          onCancel={this.closeModal}
          okText={messages('common.ok')}
          cancelText={messages("common.cancel")}
          visible={modalShow}
          title={messages('components.key401'/*操作提醒*/)}
        >
          <p style={{textAlign:'center',fontSize:'20px',margin:'10px 0px'}}>{messages('components.key402'/*您确定删除该附件?*/)}</p>
        </Modal>
      </div>
    )
  }
}

FileUpload.propTypes = {
  multiple: React.PropTypes.bool,  //上传URL
  uploadUrl: React.PropTypes.string,  //上传URL
  attachmentType: React.PropTypes.string.isRequired,  //附件类型
  defaultFileList: React.PropTypes.array,  //默认上传的文件列表
  onChange: React.PropTypes.func,  //上传成功后的回调
  maxNum: React.PropTypes.number,  //最大上传文件的数量
  placeHolder: React.PropTypes.string,  //控件配置的提示文案
  fileType: React.PropTypes.array,  //上传文件的类型
  fileSize: React.PropTypes.number,  //上传文件的大小
  isShowDefault: React.PropTypes.bool, //是否要进行回显，是否一直允许从父组件接受变化的图片列表
  disabled: React.PropTypes.bool, //是否禁用
  showMaxNum: React.PropTypes.bool, //是否显示最多上传多少图片
  data: React.PropTypes.object, //上传接口的参数
  handleDelete: React.PropTypes.func, //删除附件的回调
  setResult: React.PropTypes.func, //上传接口返回结果保存
  showFileName: React.PropTypes.bool, // 是否显示文件列表名称
  isPreViewCallBack: React.PropTypes.bool, // 附件是否预览回调
  handlePreViewCallBack: React.PropTypes.func,//附件预览回调
  accept: React.PropTypes.string,//附件只接受选择的类型
};

FileUpload.defaultProps = {
  multiple: false,
  uploadUrl: `${config.baseUrl}/api/upload/attachment`,
  defaultFileList: [],
  onChange: () => {},
  maxNum: 9,
  placeHolder: '',
  isShowDefault:false,
  disabled:false,
  showMaxNum: false,
  isPreViewCallBack: false,
  handleDelete: () => {
    return true;
  },
  setResult: (result, info) => {
    result.push(info.file.response)
  },
  showFileName: true,
  accept: constants.acceptFileTypes,
};
function mapStateToProps(state) {
  return {
    authToken: state.main.authToken
  }
}
// 注意
// defaultFileList里面的对象属性要有
//   attachmentOID,
//   fileName,
//   fileURL

export default connect(mapStateToProps)(FileUpload);
